<?php
/**
 * 获取/设置 http 传来的各种参数
 * 
 * @author rico 
 */
class Handler_http {
	/**
	 * 获取cookie值
	 * 
	 * @param string $key 
	 * @return string /array
	 */
	public static function getCookie($key) {
		if (empty($key)) {
			return $_COOKIE;
		} else {
			return isset($_COOKIE[$key])?trim($_COOKIE[$key]):false;
		} 
	} 

    /**
     * 设置cookie
     * @param <string> $name cookie名
     * @param <string> $value cookie值
     * @param <int> $expire 过期时效，以秒为单位
     * @param <string> $path 路径，默认根目录
     * @param <string> $domain 域名，默认根域名
     * @param <bool> $secure 是否只在https协议下有效
     * @param <bool> $httponly 是否只在http协议下有效，js将无法访问
     * @return <bool> 设置成功返回true，否则返回false
     */
	public static function setCookie($name,$value,$expire=0,$path='/',
		$domain='',$secure=false,$httponly=false) {
		if (empty($name)) {
			return false;
		}
        $path = empty($path) ?  '/' : $path;
        $domain = empty($domain) ? COOKIE_DOMAIN : $domain;
        return setcookie($name, $value, (int)$expire, $path, $domain , $secure, $httponly);
	} 
        
        /**
         * 设置只有php可以读取的cookie
         * 
         * @param str $name
         * @param str $value
         * @param int $expire
         * @return bool 
         */
        public static function setPhpCookie($name,$value,$expire=0) {
            return self::setCookie($name, $value, $expire, '/', '', FALSE, TRUE);
        }

        /**
     * 删除cookie
     * @param <string> $name  要删除的cookie的名字
     */
    public static function delCookie($name){
        return self::setCookie($name, "", time()-3600);
    }
        
	/**
	 * 获取session值
	 * 
	 * @param string $key 
	 * @return string /array
	 */
	public static function getSession($key) {
		if (empty($key)) {
			return $_SESSION;
		} else {
			return isset($_SESSION[$key])?trim($_SESSION[$key]):false;
		} 
	} 

	/**
	 * 设置session值
	 * 
	 * @param string $key 
	 * @param string $value 
	 * @return boolean 
	 */
	public static function setSession($key, $value,$lifeTime ='') {
            if(!empty($lifeTime)){
                session_set_cookie_params($lifeTime); 
            }
		if (empty($key)) {
			return false;
		} else {
			$_SESSION[$key] = $value;
		} 
		return true;
	}

        /**
         * 删除session
         * @param <string> $key 要删除的session的key
         * @return boolean 删除成功返回true，否则返回false
         */
        public static function delSession($key){
            return self::setSession($key, null);
        }

        /**
         * 获取当前请求的method，如POST，GET
         * @return <string> 所有值均大写，有GET, HEAD, POST, PUT
         */
        public static function getMethod(){
            return strtoupper($_SERVER['REQUEST_METHOD']);
        }

        /*
         * 设置页面无缓存
         */
        public static function setNoCache(){
            header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
            header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
            header("Pragma: no-cache");
            header("Referer: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        }

       /**
        *过滤sql关键字，转义敏感字符
        *
        * @param mixed $sql_str
        * @return mixed
        */
        public static function injectCheck($sql_str) {
//            if( is_array($sql_str) ){
//                foreach ($sql_str as $key => $value){
//                    if($key != 'backurl')
//                    $sql_str[$key]=self::injectCheck($value);
//                }
//            }
//            else if( is_string($sql_str) ){
//                //过滤sql关键字
//                $sql_str=preg_replace("/select|insert|update|delete|union|into|load_file|outfile|\*| and | or /i"," ",$sql_str);
//                //过滤html标签
//                $new_sql_str = filter_var($sql_str,FILTER_SANITIZE_STRING);
//                if (false !== $new_sql_str)
//                {
//                	$sql_str = $new_sql_str;
//                }
//                //转义单引号和双引号
//                if(get_magic_quotes_gpc()==0){
//                    $sql_str=addslashes($sql_str);
//                }
//            }
            return $sql_str;
        }
        /**
         * 检查输入参数$_POST,$_GET,$_COOKIE,$_REQUEST，过滤sql关键字，转义敏感字符
         *
         */
        public static function inputCheck()
        {
        	self::setRequestBak();
            $_POST=self::injectCheck($_POST);
            $_GET=self::injectCheck($_GET);
            $_COOKIE=self::injectCheck($_COOKIE);
            $_REQUEST=self::injectCheck($_REQUEST);
        }
        /**
         * get数组备份
         * @var array
         */
        private $_GET_BAK;
        /**
         * post数组备份
         * @var array
         */
        private $_POST_BAK;
        /**
         * cookie数组备份
         * @var array
         */
        private $_COOKIE_BAK;
        /**
         * request数组备份
         * @var array
         */
        private $_REQUEST_BAK;
        /**
         * 设置get、post、cookie、request数组的备份
         */
        private static function setRequestBak(){
        	if (DEBUG){
        		global $_GET_BAK,$_POST_BAK,$_COOKIE_BAK,$_REQUEST_BAK;
        		$_GET_BAK = $_GET;
        		$_POST_BAK = $_POST;
        		$_COOKIE_BAK = $_COOKIE;
        		$_REQUEST_BAK = $_REQUEST;
        	}
        }
        /**
         * 获取get数组备份
         * @return array
         */
        public static function getGetBak(){
        	if(DEBUG){
        		global $_GET_BAK;
        		return $_GET_BAK;
        	}else{
        		return array();
        	}
        }
        /**
         * 获取post数组备份
         * @return array
         */
        public static function getPostBak(){
        	if(DEBUG){
        		global $_POST_BAK;
        		return $_POST_BAK;
        	}else{
        		return array();
        	}
        }
        /**
         * 获取cookie数组备份
         * @return array
         */
        public static function getCookieBak(){
        	if(DEBUG){
        		global $_COOKIE_BAK;
        		return $_COOKIE_BAK;
        	}else{
        		return array();
        	}
        }
        /**
         * 获取request数组备份
         * @return array
         */
        public static function getRequestBak(){
        	if(DEBUG){
        		global $_REQUEST_BAK;
        		return $_REQUEST_BAK;
        	}else{
        		return array();
        	}
        }

        /**
         * 获取客户端IP地址
         * 在CDN下，$_SERVER ["REMOTE_ADDR"]所取的数据会有误
         * @return string 客户端的IP地址
         */
        public static function getIP()
        {
            //测试外地IP START
            self::inputCheck();
            if( !empty($_COOKIE['test_ip']) ){
                return $_COOKIE['test_ip'];
            }
            //测试外地IP END
            if( isset($_SERVER["HTTP_CDN_SRC_IP"]) ) {
                return $_SERVER["HTTP_CDN_SRC_IP"];
            }
            if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match( '/^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$/', $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            return $_SERVER["REMOTE_ADDR"];
        }

        /**
         * 获取指定的GET参数，已进行SQL Injection处理
         * @param <string> $key GET参数的key
         * @return <string> GET参数的值
         */
        public static function getGet($key){
            return self::injectCheck($_GET[$key]);
        }

        /**
         * 获取指定的POST参数，已进行SQL Injection处理
         * @param <string> $key POST参数的key
         * @return <string> POST参数的值
         */
        public static function getPOST($key){
            return self::injectCheck($_POST[$key]);
        }

        /**
         * 通过fsockopen发送异步请求，用于不需要等待响应结果的情形，以便加快程序执行速度
         * 暂仅支持HTTP协议的请求
         * @param <string> $url 含域名的完整URL地址，GET方式发送数据时要包含所有GET参数
         * @param <array> $post_data 仅POST方式时使用，以key=>value形式保存的数组
         * @return <bool> 发送成功返回服务器响应值，否则返回false
         */
        public static function sendSocketRequest($url, $post_data = null){
            //当url不是http开头时，追加http，以便后面的parse_url可以正确解析地址
            $url = trim($url);
            $pos = strpos($url, "http://");
            if( $pos === false || $pos > 1){
                $url = "http://" . $url;
            }
            //默认GET方式
            $method = "GET";
            //获取URL信息，用于生成HTTP HEADER
            $url_array = parse_url($url);
            $port = isset($url_array['port']) ? $url_array['port'] : 80;
            //日志信息
            $msg = "url: " . $url . "\r\n";
            //创建连接获得句柄，设为20秒超时
            $fp = fsockopen($url_array['host'], $port, $errno, $errstr, 20);
            //连接失败
            if(!$fp){
                //写日志
                $msg .= "connect failed";
                Log_File::writeSocketRequestLog($msg);
                return false;
            }
            $path = ( isset ($url_array['path']) ? $url_array['path'] : "/" ) . "?" . $url_array['query'];
            if( !empty($post_data) ){
                $method = "POST";
            }
            $header = $method . " " . $path;
            $header .= " HTTP/1.1\r\n";
            $header .= "Host: " . $url_array['host'] . "\r\n "; //HTTP 1.1 Host域不能省略
            /**//*以下头信息域可以省略
            $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 \r\n";
            $header .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5 \r\n";
            $header .= "Accept-Language: en-us,en;q=0.5 ";
            $header .= "Accept-Encoding: gzip,deflate\r\n";
             */

            $header .= "Connection: Close\r\n\r\n";
            //追加POST数据
            if( !empty($post_data) ){
                $post_header = "";
                foreach($post_data as $k => $v){
                    $post_header .= $k . "=" . $v . "&";
                }
                $post_str  = "Content-Type: application/x-www-form-urlencoded\r\n"; //POST数据
                $post_str .= "Content-Length: " . strlen($post_header) . " \r\n"; //POST数据的长度
                $post_str .= $post_header . "\r\n\r\n "; //传递POST数据
                $header .= $post_str;
                //向日志追加POST信息
                $msg .= $post_header . "\r\n";
            }
            fwrite($fp, $header);
            //取得返回值
            $result = "";
            
            while( !feof($fp) ) {
                $result .= fgetss($fp, 128);
            }
             
            //关闭连接
            fclose($fp);
            //写日志
            $msg .= "send success";
            Log_File::writeSocketRequestLog($msg);
            return $result;
        }

        /**
         * 获取客户端浏览器信息，含浏览器名称和版本
         * @param bool $return_as_str 返回值是否采用字符串形式，默认返回数组类型，下标分别为agent和version
         * @return mixed 客户端浏览器信息,如果未找到对应值，则返回null
         */
        public static function getBrowserInfo($return_as_str = false){
            //浏览器信息定义
            $browser_info = null;
            //定义浏览器
            $browsers = array("firefox", "msie", "chrome", "safari", "opera", "mozilla", "seamonkey", "konqueror", "netscape", 
                    "gecko", "navigator", "mosaic", "lynx", "amaya", "omniweb", "avant", "camino", "flock"); 
            //从$_SERVER中取UserAgent信息
            $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
            $match = null;
            //从useragent中查找相应的浏览器信息
            foreach($browsers as $browser) { 
                if( preg_match("#($browser)[/ ]?([0-9.]*)#", $agent, $match) ){
                    $browser_info = array();
                    $browser_info["agent"] = $match[1] ; 
                    $browser_info["version"] = $match[2] ; 
                    break ; 
                } 
            }
            //根据参数返回不同类型的值
            return is_null($browser_info) ? null : ( $return_as_str ? implode(' ', $browser_info) : $browser_info );
        }
        /**
         * 返回客户端类型
         *  $_SERVER['HTTP_ACCEPT'];//浏览器信息
            $_SERVER['HTTP_USER_AGENT'];//UA

            $_SERVER['HTTP_X_WAP_PROFILE'];//WAP特定信息 品牌机自带浏览器都会有
            $_SERVER['HTTP_UA_OS'];//手机系统 电脑为空
            $_SERVER['HTTP_VIA']; //网关信息
         *
         * 
         * @return string wap mobile web 
         */
    public static function getClientType() {
        $mob_arr = array('netfront', 'iphone', 'ipad', 'ipod', 'opera mini', 'ucweb', 'windows ce','WindowsCE', 'symbianos', 'android','mobile', 'java','BlackBerry');
        
        if (!empty($_SERVER['HTTP_X_WAP_PROFILE']) || !empty($_SERVER['HTTP_UA_OS']) || empty($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_VIA'], 'wap') !== FALSE) {
            return 'wap'; //非智能手机？ 未验证
        } elseif (stripos($_SERVER['HTTP_ACCEPT'], 'vnd.wap')) {
            return 'mobile';
        } else {
            foreach ($mob_arr as $mob) {
                if (stripos($_SERVER['HTTP_USER_AGENT'], $mob) !== FALSE && stripos($_SERVER['HTTP_USER_AGENT'] , "ipad") === FALSE) {
                    return 'mobile';
                }
            }
        }
        return 'web';
    }
    
    public static function parseSpider() {
        $spider_arr = self::_getSpider();
        foreach ($spider_arr as $agent) {
            if ($_SERVER['HTTP_USER_AGENT'] && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), $agent) !== FALSE) {
                return 'spider';
            }
        }
        return NULL;
    }
    
    private static function _getSpider(){
        return array('baidu', 'google', 'soso', 'sogou', 'yahoo', 'bing', 'msnbot', 'yodaobot', 'iaskspider', 'Ask Jeeves/Teoma', 'Exabot', 'FAST-WebCrawler');
    }
    
    /**
     * 在手机上访问pc端跳转
     */
    public static function clientRedirect(){
        if(((strpos($_SERVER['REQUEST_URI'], '/subject/') === 0))&&(!(strpos($_SERVER['REQUEST_URI'], '/public-subject/')))){
    	//if(strpos($_SERVER['REQUEST_URI'], '/subject/') === 0){
    		return false;
    	}
    	require_once(SYSTEM_PATH."config/redirect_config.php");
    	if(APP_NAME == 'phone'){
    		Redirect_Config::$defaultConfig = APP_WEB_URL;
    		$config = Redirect_Config::$phoneRedirectConfig;
    	}elseif(APP_NAME == 'default'){
    		Redirect_Config::$defaultConfig = APP_PHONE_URL;
    		$config = Redirect_Config::$defaultRedirectConfig;
    	}else{
    		return false;
    	}
    
    	$configKey = $_GET['c'].'_'.$_GET['m'];
        //临时终止对支付平台的跳转
    	if("Cashier"==$_GET['c'])
        {
            return false;
        }
    	if(array_key_exists($configKey, $config)){
    		$configPage = $config[$configKey];
    		$type = $configPage['type'];
    		if(method_exists(Redirect_Config,$type)){
    			$uri = Redirect_Config::$type($configPage);
    		}
    	}
    	
    	if(!isset($uri)){
    		$uri = Redirect_Config::$defaultConfig;
    	}
    	Handler_tool::redirect($uri);
    }
    
    public static function checkAjaxReferer(){
    	//来源
    	if (!Handler_tool::isEtpassURL($_SERVER['HTTP_REFERER'])) {
    		exit;
    	}
    }
} 
?>